package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class IWmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel>implements IWmChannelService {


    /**
     * 根据名称模糊查询分页列表
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult listByName(ChannelDto dto) {
        //根据频道名称分页查询列表
        //构建分页条件
        Page<WmChannel> page = new Page<>(dto.getPage(),dto.getSize());
        //构建查询条件
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        //判断频道名称是否为空,如果为空,添加条件
        if (!StringUtils.isEmpty(dto.getName())){
            queryWrapper.like(WmChannel::getName ,dto.getName());
        }
        //执行分页查询
        Page<WmChannel> iPage = this.page(page, queryWrapper);
        long total = iPage.getTotal();
        //创建响应的分页对象  填充数据
        PageResponseResult result = new PageResponseResult<>(dto.getPage(), dto.getSize(), total, iPage.getRecords());
        return result;
    }

    /**
     * 新增频道
     * @param channel
     * @return
     */
    @Override
    public ResponseResult saveWmChannel(WmChannel channel) {
        //1.查看数据组有没有该名字的频道
            //1.1.创建查询条件
        Wrapper<WmChannel> query = new LambdaQueryWrapper<>();
        ((LambdaQueryWrapper<WmChannel>) query).like(WmChannel::getName,channel.getName());
            //1.2.查询
        WmChannel wmChannel = this.getOne(query);
        //2.如果有则抛出异常提示
        if (!StringUtils.isEmpty(wmChannel)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //3.如果没有则新加
        this.save(channel);
        //返回成功结果
        return ResponseResult.okResult();
    }

    /**
     * 修改频道
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateChannel(WmChannel dto) {
        //判断数据库有无该频道
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        query.eq(WmChannel::getName,dto.getName());
        WmChannel one = this.getOne(query);
        if (!StringUtils.isEmpty(one)){
            //已有该频道
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        this.updateById(dto);
        return ResponseResult.okResult();
    }


}
